using DG.Tweening;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Projectile : MonoBehaviour
{
    public SpriteRenderer SR;
    public float remainTime;
    private Transform target;

    private float initRotationZ;
    private Vector3 lastPosition;
    private Vector3 planeNormal;
    // Start is called before the first frame update
    void Start()
    {
        // SR.color = new Color(1f, 1f, 1f, 0f);
        initRotationZ = SR.transform.localRotation.eulerAngles.z;
        planeNormal = new Vector3(0f, Mathf.Sqrt(3f) / 2f, 0.5f);
        lastPosition = transform.position;

        StartCoroutine(EffectCoroutine());
    }

    private void Update()
    {
        Vector3 dir = transform.position - lastPosition;
        dir = Vector3.ProjectOnPlane(dir, planeNormal);
        float scaleX = transform.localScale.x > 0 ? 1f : -1f;

        if (dir.magnitude >= 0.05f)
        {
            float dz = Mathf.Atan2(dir.y, dir.x) * 180f / 3.14159f;
            float z = initRotationZ + dz * scaleX;
            if (scaleX > 0)
                z += 180f;
            SR.transform.localRotation = Quaternion.Euler(0f, 0f, z);
 
        }
        lastPosition = transform.position;
    }

    public void SetTarget(Transform newTarget)
    {
        target = newTarget;
    }

    IEnumerator EffectCoroutine()
    {
        float jumpTime = 0.3f;
        Vector3 targetPos = target.position;
        Vector3 height = new Vector3(0f, 0.5f, -Mathf.Sqrt(3f) / 2f) * 4f;
        Vector3 mid = targetPos.y > transform.position.y ? targetPos + height : transform.position + height;
        mid.x = (targetPos.x + transform.position.x) / 2f;
        transform.DOMoveX(targetPos.x, jumpTime * 2f).SetEase(Ease.Linear);
        transform.DOMoveY(mid.y, jumpTime).SetEase(Ease.OutCubic);
        transform.DOMoveZ(mid.z, jumpTime).SetEase(Ease.OutCubic);
        yield return new WaitForSeconds(jumpTime);

        transform.DOMoveY(targetPos.y, jumpTime).SetEase(Ease.InCubic);
        transform.DOMoveZ(targetPos.z, jumpTime).SetEase(Ease.InCubic);

        yield return new WaitForSeconds(jumpTime + remainTime);
        Destroy(gameObject);
        yield break;
    }
}
